//微信支付，调用payjs收费

const Router = require('koa-router')
const { query,constInsert,exeTrans,constUpdate,paging,constructWhere } = require('../db')
const { getRes } = require('../res')
const { formatDate,get_pay_one,pay_prex } = require('../util')
let paytool = require('../paytools')
let pay = new Router()

pay.post('/check_pay_status', async(ctx) => {
    let qry = ctx.request.body;
    try{
        let sql = "select * from pay where out_trade_no = ? and status=1";
        let res = await query(sql,qry.order_id);

        if(res.length>0){
            ctx.response.body = getRes(0,true);
        }else{
            ctx.response.body = getRes(0,false);
        }
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

pay.post('/start_pay', async(ctx) => {
    let qry = ctx.request.body;
    try {
        let tranFunc = async (conn) => {//执行事务
            try {
                let user = ctx.user;

                let pay_info = get_pay_one(qry.type)

                if(pay_info==null){
                    return Promise.resolve(getRes(3));
                }

                var total_fee = pay_info.price;

                let date = new Date();
                let obj = {
                    total_fee:total_fee,
                    user_id:user.id,
                    status:0,
                    creatTime:date,
                    month:pay_info.month
                }
                let payres = await constInsert('pay',obj);
                console.log(payres);
                
                var params = {
                    'mchid': '商户号',     //商户号
                    'total_fee': total_fee,     //金额。单位：分
                    'out_trade_no': formatDate(date,"yyyyMMddhhmmssS")+payres.insertId, //用户端自主生成的订单号
                    'body': '零柒插件',           //订单标题
                    'attach': '',       //用户自定义数据，在notify的时候会原样返回
                    'notify_url': 'http://'+pay_prex()+'/api/login/paynotify'             //接收微信支付异步通知的回调地址。必须为可直接访问的URL，不能带参数、session验证、csrf验证。留空则不通知
                };
                console.log(params);
                let res = await paytool.native(params);
                console.log(res);
                if(res.return_code==0){
                    return Promise.resolve(getRes(3));
                }
                
                let updateobj = {
                    out_trade_no:res.out_trade_no,
                    payjs_order_id:res.payjs_order_id,
                    id:payres.insertId
                };

                let p = {
                    id:res.out_trade_no,
                    url:res.qrcode
                }

                await constUpdate('pay',updateobj);

                return Promise.resolve(getRes(0,p));
            }catch (e){
                return Promise.reject(e);
            }
        }
        let r = await exeTrans(tranFunc);
        
        ctx.response.body = r;
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

module.exports = pay;